import type {AxiosRequestConfig, AxiosResponse} from 'axios';
import axios from 'axios';
import {ElDialog, ElMessage} from 'element-plus';
import {useUserStore} from '@/store';
import {getToken} from '@/utils/auth';
import qs from "query-string";

export interface HttpResponse<T = unknown> {
    status: number;
    msg: string;
    code: number;
    data: T;
}

if (import.meta.env.VITE_API_BASE_URL) {
    axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
}

axios.interceptors.request.use(
    // @ts-ignore
    (config: AxiosRequestConfig) => {
        // let each request carry token
        // this example using the JWT token
        // Authorization is a custom headers key
        // please modify it according to the actual situation
        const token = getToken();
        if (token) {
            if (!config.headers) {
                config.headers = {};
            }
            config.headers.Authorization = `Bearer ${token}`;
        }
        if (config.method === 'get' || config.method === 'delete') {
            config.paramsSerializer = (params) => {
                // @ts-ignore
                return qs.stringify(params, {arrayFormat: 'repeat'})
            }
        }
        return config;
    },
    (error) => {
        // do something
        return Promise.reject(error);
    }
);
// add response interceptors
axios.interceptors.response.use(
    (response: AxiosResponse) => {
        const res = response.data;
        // 根据状态码判断
        // 50001: 未登录;
        if ([50001].includes(res.code)) {
            ElDialog.warning({
                title: '系统提示',
                content:
                    '您已登出，您可以取消留在该页面，或重新登录',
                okText: '重新登录',
                async onOk() {
                    const userStore = useUserStore();
                    userStore.logoutCallBack();
                    window.location.reload();
                },
            });
            return Promise.reject();
        } else if (res.code === 500) {
            ElMessage.warning({
                message: res.msg,
                duration: 2 * 1000,
            });
        } else if (res.code !== 200) {
            console.log(res.msg);
            ElMessage.warning({
                message: res.msg,
                duration: 2 * 1000,
            });
        }
        return res;
    },
    (error) => {
        const res = error.response;
        if (res.status === 401) {
            ElDialog.error({
                title: '系统提示',
                content:
                    '您已登出，您可以取消留在该页面，或重新登录',
                okText: '重新登录',
                async onOk() {
                    const userStore = useUserStore();

                    userStore.logoutCallBack();
                    window.location.reload();
                },
            });
        } else if (res.status === 404) {
            ElMessage.warning({
                message: "请求路径不存在",
                duration: 2 * 1000,
            });
        } else if (res.status === 500) {
            ElMessage.warning({
                message: "请求异常，请联系管理员",
                duration: 2 * 1000,
            });
        } else {
            ElMessage.error({
                message: error.msg || 'Request Error',
                duration: 2 * 1000,
            });
        }
        return Promise.reject(error);
    }
);
